<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          class="!w-240px"
        >
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="监护人电话" prop="guardianPhone">
        <el-input
          v-model="queryParams.guardianPhone"
          placeholder="请输入监护人电话"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="家庭地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入家庭地址"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="在读" :value="0" />
          <el-option label="毕业" :value="1" />
          <el-option label="退学" :value="2" />
          <el-option label="休学" :value="3" />
          <el-option label="转学" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['ao:student:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['ao:student:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['ao:student:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="studentId"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="学号" align="center" prop="studentNo" width="120" />
      <el-table-column label="姓名" align="center" prop="name" width="100" />
      <el-table-column label="性别" align="center" prop="gender" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.gender === 1 ? 'primary' : 'success'">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phone" width="130" />
      <el-table-column label="监护人电话" align="center" prop="guardianPhone" width="130" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" width="80">
        <template #default="scope">
          <el-button type="primary" link @click="openDetail(scope.row)">
            <Icon icon="ep:view" />
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.studentId)"
            v-hasPermi="['ao:student:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.studentId)"
            v-hasPermi="['ao:student:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <StudentForm ref="formRef" @success="getList" />

  <!-- 详情弹窗 -->
  <el-dialog v-model="detailVisible" title="学生详情" width="800px" append-to-body>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="学号">{{ detailData.studentNo }}</el-descriptions-item>
      <el-descriptions-item label="姓名">{{ detailData.name }}</el-descriptions-item>
      <el-descriptions-item label="性别">
        <el-tag :type="detailData.gender === 1 ? 'primary' : 'success'">
          {{ detailData.gender === 1 ? '男' : '女' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="身份证号">{{ detailData.idCard }}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{ detailData.phone }}</el-descriptions-item>
      <el-descriptions-item label="邮箱">{{ detailData.email }}</el-descriptions-item>
      <el-descriptions-item label="所属班级ID">{{ detailData.classId }}</el-descriptions-item>
      <el-descriptions-item label="所属专业ID">{{ detailData.majorId }}</el-descriptions-item>
      <el-descriptions-item label="入学日期">{{ formatDate(detailData.enrollmentDate) }}</el-descriptions-item>
      <el-descriptions-item label="入学学期ID">{{ detailData.enrollmentTermId }}</el-descriptions-item>
      <el-descriptions-item label="毕业日期">{{ formatDate(detailData.graduationDate) }}</el-descriptions-item>
      <el-descriptions-item label="当前学期数">{{ detailData.currentSemester }}</el-descriptions-item>
      <el-descriptions-item label="已获得学分">{{ detailData.totalCredits }}</el-descriptions-item>
      <el-descriptions-item label="平均绩点">{{ detailData.gpa }}</el-descriptions-item>
      <el-descriptions-item label="监护人姓名">{{ detailData.guardianName }}</el-descriptions-item>
      <el-descriptions-item label="监护人电话">{{ detailData.guardianPhone }}</el-descriptions-item>
      <el-descriptions-item label="家庭地址" :span="2">{{ detailData.address }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="getStatusType(detailData.status)">
          {{ getStatusText(detailData.status) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ formatDate(detailData.createTime) }}</el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="detailVisible = false">关闭</el-button>
      <el-button type="primary" @click="openForm('update', detailData.studentId)">编辑</el-button>
    </template>
  </el-dialog>
  <!-- 表单弹窗：导入 -->
  <StudentImportForm ref="importFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { StudentApi, Student } from '@/api/ao/student'
import StudentForm from './StudentForm.vue'
import StudentImportForm from './StudentImportForm.vue'

/** 学生信息 列表 */
defineOptions({ name: 'Student' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Student[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const detailVisible = ref(false) // 详情弹窗显示状态
const detailData = ref({}) // 详情数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  studentNo: undefined,
  name: undefined,
  gender: undefined,
  idCard: undefined,
  phone: undefined,
  email: undefined,
  classId: undefined,
  majorId: undefined,
  enrollmentDate: [],
  enrollmentTermId: undefined,
  graduationDate: [],
  currentSemester: undefined,
  totalCredits: undefined,
  gpa: undefined,
  guardianName: undefined,
  guardianPhone: undefined,
  address: undefined,
  status: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StudentApi.getStudentPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 导入按钮操作 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StudentApi.deleteStudent(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除学生信息 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await StudentApi.deleteStudentList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Student[]) => {
  checkedIds.value = records.map((item) => item.studentId);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StudentApi.exportStudent(queryParams)
    download.excel(data, '学生信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 状态格式化 */
const getStatusText = (status: number) => {
  const statusMap = {
    0: '在读',
    1: '毕业',
    2: '退学',
    3: '休学',
    4: '转学'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status: number) => {
  const typeMap = {
    0: 'success',
    1: 'info',
    2: 'danger',
    3: 'warning',
    4: 'primary'
  }
  return typeMap[status] || 'info'
}

/** 打开详情弹窗 */
const openDetail = (row: Student) => {
  detailData.value = { ...row }
  detailVisible.value = true
}

/** 日期格式化 */
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>